import React, { useEffect, useRef, useState } from 'react'
import ProTable from '@ant-design/pro-table'
import { Button, message, Modal } from 'antd'
import { PageContainer } from '@ant-design/pro-layout'
import { deleteRole, getRoleList } from '@/services/role'
import { PlusOutlined } from '@ant-design/icons'
import { getPermissionList } from '@/services/permission'
import ProTableConfig from '@/pages/Exam/TestList/ProTableConfig'
import CreateOrEdit from '@/pages/Configuration/Role/components/CreateOrEdit'
import GetTime from '@/components/GetTime'

const Index = () => {
  // 控制添加修改模态框的显示与隐藏
  const [isModalVisible, setIsModalVisible] = useState(false)
  // 获取权限数据
  const [permission, setPermission] = useState([])
  // 控制删除模态框
  const [visible, setVisible] = useState(false)
  // 将要被批量选中的id
  const [selectedRowKeys, setSelectedRowKeys] = useState(undefined)
  // 将要被单个选中的id
  const [ids, setIds] = useState(undefined)
  // 判断是单个删除还是批量删除
  const [status, setStatus] = useState(false)
  const actionRef = useRef()
  // 是否显示添加模态框
  const isShowModal = (show, id = undefined) => {
    setIds(id)
    setIsModalVisible(show)
  }

  // 获取权限数据
  useEffect(async () => {
    const res = await getPermissionList()
    setPermission(res.data)
  }, [])

  // 获取列表数据
  const getData = async (params) => {
    // 更改默认属性名 current
    params = JSON.parse(JSON.stringify(params).replace(/current/g, 'page'))
    const response = await getRoleList(params)

    return {
      data: response.data,
      success: true,
      total: response.meta.pagination.total
    }
  }

  // 获取单个删除的id
  const showModel = (value) => {
    setVisible(true)
    setIds(value)
  }

// 获取角色的详情
//   const updateModel = (show, id) => {
//     setIds(id)
//     setIsModalVisible(show)
//   }

  // 拿到批量选中的id
  const onSelectDel = (value) => {
    if (value === undefined) {
      message.error('请选择将要删除的角色')
      return
    }
    setSelectedRowKeys(value.toString())
    setVisible(true)
    setStatus(true)
  }

  /**
   * 多选操作
   * @param selectedRowKeys
   */
  const onSelectChange = selectedRowKeys => {
    setSelectedRowKeys(selectedRowKeys)
  }

  /**
   * 多选配置
   * @type {{onChange: onSelectChange, selectedRowKeys: unknown}}
   */
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  }

  // 执行删除的方法
  const confirmRole = async (id) => {

    const deleteRes = await deleteRole(id)

    if (deleteRes.status === undefined) {
      message.success('删除成功')
      // 关闭模态框
      setVisible(false)

      setStatus(false)

      actionRef.current.reloadAndRest()

    }
  }

  // 删除操作
  const delRole = () => {
    confirmRole(status === false ? ids : selectedRowKeys)
    setSelectedRowKeys([])
  }

  // 遍历权限数据进行树状显示
  const treeData = permission.map((item) => {
    return {
      key: item.id,
      value: item.id,
      title: item.cn_name,
      children: item.children.map((item) => {
        return {
          key: item.id,
          value: item.id,
          title: '---' + item.cn_name,
        }
      })
    }
  })

  // 表格列标题
  const columns = [
    {
      title: 'ID',
      width: 120,
      dataIndex: 'id',
    },
    {
      title: '角色名称',
      width: 120,
      dataIndex: 'cn_name',
    },
    {
      title: '唯一标识',
      width: 120,
      dataIndex: 'name',
    },
    {
      title: '操作',
      width: 80,
      render: (_, record) => [
        <Button
          key="action"
          type="primary"
          size="small"
          style={{ marginRight: 20 }}
          onClick={() => isShowModal(true, record.id)}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="danger"
          size="small"
          onClick={() => showModel(record.id)}
        >
          删除
        </Button>
      ],
    },
  ]

  return (
    <PageContainer header={{
      extra: [
        <GetTime key="getTime"/>
      ]
    }}>
      <Modal
        centered
        visible={visible}
        onOk={delRole}
        onCancel={() => setVisible(false)}
        width={500}
      >
        <p>确定要删除吗？</p>
      </Modal>
      <ProTable
        {...ProTableConfig}
        columns={columns}
        rowSelection={rowSelection}
        actionRef={actionRef}
        options={{ fullScreen: false, reload: true, setting: false }}
        toolbar={{
          title: '角色列表',
        }}
        toolBarRender={() => [
          <Button key="button" icon={<PlusOutlined/>} type="primary" onClick={() => isShowModal(true)}>
            添加角色
          </Button>,
          <Button type="primary" key="primary" danger onClick={() => onSelectDel(selectedRowKeys)}>
            批量删除
          </Button>,
        ]}
        request={params => getData(params)}
        scroll={{ x: 1300 }}
        search={false}
        rowKey="id"
      />
      {
        !isModalVisible ? '' :
          <CreateOrEdit
            isModalVisible={isModalVisible}
            isShowModal={isShowModal}
            ids={ids}
            treeData={treeData}
            actionRef={actionRef}
          />
      }
    </PageContainer>
  )
}
export default Index

